﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SPMonster2010
{
    public partial class SPMForm : Form
    {
        SPFarm myfarm = SPFarm.Local;

        public SPMForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 트리메뉴 기동
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripMenuItem1_1_Click(object sender, EventArgs e)
        {
            TreeNode rootNode = AddNewNode("SharePoint Farm", SPMtreeView.Nodes, false);
            TreeNode webserviceNode = AddNewNode("SPWebServices", rootNode.Nodes, true);
            TreeNode serviceNode = AddNewNode("SPServices", rootNode.Nodes, true);
            TreeNode serverNode = AddNewNode("Servers", rootNode.Nodes, true);

            SPMtreeView.NodeMouseDoubleClick += SPMtreeView_NodeMouseDoubleClick;
            SPMtreeView.AfterExpand += SPMtreeView_AfterExpand;
            rootNode.Expand();
        }

        /// <summary>
        /// 노드를 더블클릭할 때 우측에 탭컨트롤을 표시한다.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void SPMtreeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            tabControl_SPList.Visible = false;
            dataGridView_SPListItem.DataSource = null;
            comboBox_SPList_2.Items.Clear();

            switch (SPMtreeView.SelectedNode.Tag.ToString().Split('^')[0])
            {
                case "SPList":
                    tabControl_SPList.Visible = true;
                    tabControl_SPList.Dock = DockStyle.Fill;
                    break;
                case "SPDocLib":
                    tabControl_SPList.Visible = true;
                    tabControl_SPList.Dock = DockStyle.Fill;
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 노드를 펼칠 때 하위 항목을 채운다
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void SPMtreeView_AfterExpand(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Nodes.Count > 0 && e.Node.Nodes[0].Text == "작업중입니다.")
            {
                e.Node.Nodes.Clear();

                SPMtreeView.SelectedNode = e.Node;

                switch (SPMtreeView.SelectedNode.Text)
                {
                    case "SPWebServices":
                        foreach (SPService myService in myfarm.Services)
                        {
                            if (myService is SPWebService)
                            {
                                AddNewNode(myService.TypeName, myService.Id.ToString(), true);
                            }
                        }
                        break;
                    case "SPServices":
                        foreach (SPService myService in myfarm.Services)
                        {
                            if (!(myService is SPWebService))
                            {
                                AddNewNode(myService.TypeName, "", true);
                            }
                        }
                        break;
                    case "Servers":
                        foreach (SPServer myServer in myfarm.Servers)
                        {
                            AddNewNode(myServer.DisplayName, "", true);
                        }
                        break;
                    case "Microsoft SharePoint Foundation Web Application":
                        SPService _myService = myfarm.Services[new Guid(SPMtreeView.SelectedNode.Tag.ToString())];
                        SPWebService webService = (SPWebService)_myService;
                        foreach (SPWebApplication webApp in webService.WebApplications)
                        {
                            AddNewNode(webApp.Name, "SPWebApp^" + webApp.Id.ToString(), true);
                        }
                        break;
                    case "Microsoft SharePoint Foundation 웹 응용 프로그램":
                        SPService _myService3 = myfarm.Services[new Guid(SPMtreeView.SelectedNode.Tag.ToString())];
                        SPWebService webService3 = (SPWebService)_myService3;
                        foreach (SPWebApplication webApp in webService3.WebApplications)
                        {
                            AddNewNode(webApp.Name, "SPWebApp^" + webApp.Id.ToString(), true);
                        }
                        break;
                    default:
                        switch (SPMtreeView.SelectedNode.Tag.ToString().Split('^')[0])
                        {
                            case "SPWebApp":
                                SPService _myService2 = myfarm.Services[new Guid(SPMtreeView.SelectedNode.Parent.Tag.ToString())];
                                SPWebService webService2 = (SPWebService)_myService2;
                                SPWebApplication webApp2 = webService2.WebApplications[new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[1])];
                                foreach (SPSite site in webApp2.Sites)
                                {
                                    AddNewNode(site.Url, "SPSite^" + site.ID.ToString(), true);
                                }
                                break;
                            case "SPSite":
                                SPSite sitecol = new SPSite(new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[1]));
                                SPWeb web = sitecol.RootWeb;
                                AddNewNode(web.Title, "SPWeb^" + sitecol.ID.ToString() + "^" + web.ID.ToString(), true);
                                break;
                            case "SPWeb":
                                SPSite sitecol2 = new SPSite(new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[1]));
                                SPWeb web2 = sitecol2.AllWebs[new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[2])];
                                AddNewNode("Lists", "SPLists^" + sitecol2.ID.ToString() + "^" + web2.ID.ToString(), true);
                                AddNewNode("Sites", "SPWebs^" + sitecol2.ID.ToString() + "^" + web2.ID.ToString(), true);
                                break;
                            case "SPLists":
                                SPSite sitecol21 = new SPSite(new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[1]));
                                SPWeb web21 = sitecol21.AllWebs[new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[2])];
                                foreach (SPList list in web21.Lists)
                                {
                                    if ((Convert.ToInt32(list.Hidden) * Convert.ToInt32(ToolStripMenuItem2_1_1.Checked)) == 0)
                                    {
                                        if (list.BaseTemplate == SPListTemplateType.DocumentLibrary || list.BaseTemplate == SPListTemplateType.HomePageLibrary || list.BaseTemplate == SPListTemplateType.PictureLibrary || list.BaseTemplate == SPListTemplateType.ThemeCatalog || list.BaseTemplate == SPListTemplateType.WebPageLibrary || list.BaseTemplate == SPListTemplateType.WebPartCatalog || list.BaseTemplate == SPListTemplateType.ListTemplateCatalog || list.BaseTemplate == SPListTemplateType.MasterPageCatalog)
                                        {
                                            AddNewNode(list.Title, "SPDocLib^" + sitecol21.ID.ToString() + "^" + web21.ID.ToString() + "^" + list.ID.ToString(), false);
                                        }
                                        else
                                        {
                                            AddNewNode(list.Title, "SPList^" + sitecol21.ID.ToString() + "^" + web21.ID.ToString() + "^" + list.ID.ToString(), false);
                                        }
                                    }
                                }
                                break;
                            case "SPWebs":
                                SPSite sitecol22 = new SPSite(new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[1]));
                                SPWeb web22 = sitecol22.AllWebs[new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[2])];
                                foreach (SPWeb web221 in web22.Webs)
                                {
                                    AddNewNode(web221.Title, "SPWeb^" + sitecol22.ID.ToString() + "^" + web221.ID.ToString(), true);
                                }
                                break;
                            case "SPDocLib":
                                SPSite sitecol3 = new SPSite(new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[1]));
                                SPWeb web3 = sitecol3.AllWebs[new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[2])];
                                SPList list3 = web3.Lists[new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[3])];
                                //foreach (SPListItem item in list3.Items)
                                //{
                                //    AddNewNode(item.File.Name, "SPFile^" + item.UniqueId.ToString(), false);
                                //}
                                break;
                            case "SPList":
                                SPSite sitecol4 = new SPSite(new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[1]));
                                SPWeb web4 = sitecol4.AllWebs[new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[2])];
                                SPList list4 = web4.Lists[new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[3])];
                                //foreach (SPListItem item in list4.Items)
                                //{
                                //    if (item.Fields.ContainsField("Title"))
                                //    {
                                //        AddNewNode(item.Title, "SPListItem^" + item.UniqueId.ToString(), false);
                                //    }
                                //    else
                                //    {
                                //        AddNewNode(item.ID.ToString(), "SPListItem^" + item.UniqueId.ToString(), false);
                                //    }
                                //}
                                break;
                            default:
                                break;
                        }
                        break;
                }

            }
        }

        /// <summary>
        /// 트리메뉴 초기화
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStripMenuItem1_2_Click(object sender, EventArgs e)
        {
            SPMtreeView.Nodes.Clear();
        }

        private TreeNode AddNewNode(string _nodeName, String myTag, bool addSubnode)
        {
            TreeNode _Node = new TreeNode(_nodeName);
            _Node.Tag = myTag;
            SPMtreeView.SelectedNode.Nodes.Add(_Node);
            if (addSubnode)
            {
                AddDefaultSubNode(_Node);
            }
            return _Node;
        }

        private TreeNode AddNewNode(string _nodeName, TreeNodeCollection _nodeCol, bool addSubnode)
        {
            TreeNode _Node = new TreeNode(_nodeName);
            _Node.Tag = "";
            _nodeCol.Add(_Node);
            if (addSubnode)
            {
                AddDefaultSubNode(_Node);
            } 
            return _Node;
        }

        private void AddDefaultSubNode(TreeNode _node)
        {
            TreeNode _subNode = new TreeNode("작업중입니다.");
            _node.Nodes.Add(_subNode);
        }

        private void ToolStripMenuItem2_1_1_CheckedChanged(object sender, EventArgs e)
        {
            MessageBox.Show("트리메뉴를 초기화해야 적용됩니다.");
        }

        /// <summary>
        /// 리스트 아이템 가져오기 버튼
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SPList_GetItem_Click(object sender, EventArgs e)
        {
            //if (comboBox_SPList_1.SelectedText == "")
            //{
            //    comboBox_SPList_1.SelectedIndex = 0;
            //}

            SPSite sitecol = new SPSite(new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[1]));
            SPWeb web = sitecol.AllWebs[new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[2])];
            SPList list = web.Lists[new Guid(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[3])];

            SPQuery query = new SPQuery();
            if (comboBox_SPList_2.SelectedItem == null || comboBox_SPList_2.SelectedItem.ToString() == "" || comboBox_SPList_3.SelectedItem.ToString() == "" || textBox_SPList_1.Text == "")
            {
                query.Query = "";
            }
            else
            {
                string myfType = list.Fields.GetFieldByInternalName(comboBox_SPList_2.SelectedItem.ToString()).Type.ToString();

                query.Query = string.Concat(
                    "<Where>",
                        "<Eq>",
                            "<FieldRef Name='" + comboBox_SPList_2.SelectedItem.ToString() + "' />",
                            "<Value Type='" + myfType + "'>" + textBox_SPList_1.Text + "</Value>",
                        "</Eq>",
                    "</Where>"
                    );
            }
            query.RowLimit = uint.Parse(comboBox_SPList_1.SelectedItem.ToString());
            query.ViewAttributes = "Scope=\"RecursiveAll\"";

            DataTable itemTable = list.GetItems(query).GetDataTable();

            if (itemTable != null)
            {
                dataGridView_SPListItem.DataSource = itemTable;
                dataGridView_SPListItem.AutoGenerateColumns = true;
                dataGridView_SPListItem.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);


                comboBox_SPList_2.Items.Clear();
                comboBox_SPList_2.SelectedItem = null;
                foreach (DataColumn col in itemTable.Columns)
                {
                    comboBox_SPList_2.Items.Add(col.ColumnName);
                }
            }
            else
            {
                dataGridView_SPListItem.DataSource = null;
            }
        }

        /// <summary>
        /// 필드값 변경 버튼
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SPList_ChangeFieldValue_Click(object sender, EventArgs e)
        {
            List<string> myIDStrings = new List<string>();

            foreach (DataGridViewRow row in dataGridView_SPListItem.Rows)
            {
                if (row.Cells["Column_Check_1"].Value != null && row.Cells["Column_Check_1"].Value.ToString() == "True")
                {
                    myIDStrings.Add(row.Cells["ID"].Value.ToString());
                }
            }

            string[] myIDs = myIDStrings.ToArray();

            if (myIDs.Length == 0)
            {
                MessageBox.Show("선택된 아이템이 없습니다.");
            }
            else
            {
                SPMData_ItemCollection myItems = new SPMData_ItemCollection(SPMtreeView.SelectedNode.Tag.ToString().Split('^')[1], SPMtreeView.SelectedNode.Tag.ToString().Split('^')[2], SPMtreeView.SelectedNode.Tag.ToString().Split('^')[3], myIDs);

                Form_SPList_ChangeFieldValue frm = new Form_SPList_ChangeFieldValue(myItems, ToolStripMenuItem2_1_2.Checked);
                frm.StartPosition = FormStartPosition.CenterParent;
                frm.Owner = this;
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    dataGridView_SPListItem.DataSource = null;
                }
            }

        }

        /// <summary>
        /// 선택된 아이템 복사하기
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SPList_CopyItem_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 전체 선택
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SPList_selectAll_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView_SPListItem.Rows)
            {
                row.Cells["Column_Check_1"].Value = true;
            }
        }

        /// <summary>
        /// 선택반전
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SPList_selectReverse_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView_SPListItem.Rows)
            {
                if (row.Cells["Column_Check_1"].Value != null && row.Cells["Column_Check_1"].Value.ToString() == "True")
                {
                    row.Cells["Column_Check_1"].Value = false;
                }
                else
                {
                    row.Cells["Column_Check_1"].Value = true;
                }
            }
        }
    }
}
